import { GssGetScene } from "@/api/api";

export const SHARE_ACTION_ASSIST_COUPON = "AssistCoupon"; // 优惠券助力
export const SHARE_ACTION_GIVE_COUPON = "GiveCoupon"; // 领取赠送优惠券
export const SHARE_ACTION_RECOMMEND = "Recommend"; // 推荐

export function buildShareSceneMap(action, payload) {
  return {
    action,
    payload,
  };
}
export function buildShareQueryParams(action, payload) {
  return `action=${action}&payload=${encodeURIComponent(
    JSON.stringify(payload)
  )}`;
}

export function handleShare(action, payload, userStore) {
  console.log("handleShare", action, payload);
  payload = decodeURIComponent(payload);
  switch (action) {
    case SHARE_ACTION_ASSIST_COUPON:
      // console.log("AssistCoupon", payload);
      uni.navigateTo({
        url: `/subpages/my/couponDetail?action=${action}&payload=${payload}`,
      });
      break;
    case SHARE_ACTION_GIVE_COUPON:
      // console.log("GiveCoupon", payload);
      uni.navigateTo({
        url: `/subpages/my/couponDetail?action=${action}&payload=${payload}`,
      });
      break;
    case SHARE_ACTION_RECOMMEND:
      console.log(SHARE_ACTION_RECOMMEND, payload);
      if (!userStore.isLogin) {
        const { Referrer } = JSON.parse(payload);
        userStore.setReferrer(Referrer);
        uni.navigateTo({
          url: "/subpages/account/login",
        });
      }
      break;
    default:
      console.error("Unknown share action", action);
  }
}

export async function handleShareScene(scene, userStore) {
  try {
    let sceneMapId = decodeURIComponent(scene);
    if (sceneMapId.startsWith('scenemap:')) {
      sceneMapId = sceneMapId.replace('scenemap:', '');
    }
    const data = await GssGetScene(sceneMapId);
    const { action, payload } = JSON.parse(data);
    handleShare(action, JSON.stringify(payload), userStore);
  } catch (e) {
    console.error(e);
  }
}
